const Merge = require("../template")

function testMergeComplexScenarios() {
  console.log(
    "1. 复杂合并系统测试:",
    (() => {
      const target = {
        user: {
          profile: {
            name: 'John',
            age: 30,
            preferences: {
              theme: 'dark',
              lang: 'en'
            }
          },
          settings: {
            notifications: true,
            privacy: 'public'
          }
        },
        data: {
          items: [1, 2, 3],
          config: {
            version: '1.0.0',
            features: ['feature1', 'feature2']
          }
        }
      }
      
      const source = {
        user: {
          profile: {
            age: 31,
            city: 'NYC',
            preferences: {
              lang: 'zh'
            }
          },
          settings: {
            privacy: 'private'
          }
        },
        data: {
          items: [4, 5, 6],
          config: {
            version: '2.0.0',
            features: ['feature3']
          }
        }
      }
      
      // 复杂合并操作
      const merged = Merge.merge(target, source)
      
      return merged.user.profile.name === 'John' &&
             merged.user.profile.age === 31 &&
             merged.user.profile.city === 'NYC' &&
             merged.user.profile.preferences.theme === 'dark' &&
             merged.user.profile.preferences.lang === 'zh' &&
             merged.user.settings.notifications === true &&
             merged.user.settings.privacy === 'private' &&
             JSON.stringify(merged.data.items) === JSON.stringify([4, 5, 6]) &&
             merged.data.config.version === '2.0.0' &&
             JSON.stringify(merged.data.config.features) === JSON.stringify(['feature3'])
    })()
  )

  console.log(
    "2. 合并动态负载测试:",
    (() => {
      const target = { base: 1 }
      const sources = Array.from({ length: 100 }, (_, i) => ({
        [`dynamic${i}`]: i,
        base: i + 1
      }))
      
      // 动态负载测试
      const loadPatterns = [
        { method: 'merge', sources: sources.slice(0, 10) },
        { method: 'mergeImmutable', sources: sources.slice(0, 10) },
        { method: 'mergeWith', sources: sources.slice(0, 10), customizer: (obj, src) => src },
        { method: 'mergeWithArrayStrategy', sources: sources.slice(0, 10), strategy: 'concat' },
        { method: 'mergeWithCondition', sources: sources.slice(0, 10), predicate: () => true }
      ]
      
      let successCount = 0
      loadPatterns.forEach(pattern => {
        try {
          let result
          if (pattern.method === 'merge') {
            result = Merge.merge(target, ...pattern.sources)
          } else if (pattern.method === 'mergeImmutable') {
            result = Merge.mergeImmutable(target, ...pattern.sources)
          } else if (pattern.method === 'mergeWith') {
            result = Merge.mergeWith(target, pattern.sources[0], pattern.customizer)
          } else if (pattern.method === 'mergeWithArrayStrategy') {
            result = Merge.mergeWithArrayStrategy(target, ...pattern.sources, pattern.strategy)
          } else if (pattern.method === 'mergeWithCondition') {
            result = Merge.mergeWithCondition(target, ...pattern.sources, pattern.predicate)
          }
          
          if (result && Object.keys(result).length > 0) {
            successCount++
          }
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 4
    })()
  )

  console.log(
    "3. 合并边界条件测试:",
    (() => {
      const boundaryTests = [
        () => Merge.merge({}, {}), // 空对象
        () => Merge.merge({ a: 1 }, null), // null源
        () => Merge.merge({ a: 1 }, undefined), // undefined源
        () => Merge.merge(null, { b: 2 }), // null目标
        () => Merge.merge(undefined, { b: 2 }), // undefined目标
        () => Merge.merge({ a: 1 }, { a: null }), // null值
        () => Merge.merge({ a: 1 }, { a: undefined }), // undefined值
        () => Merge.merge({ a: 1 }, { a: NaN }), // NaN值
        () => Merge.merge({ a: 1 }, { a: Infinity }), // Infinity值
        () => Merge.merge({ a: 1 }, { a: -Infinity }), // -Infinity值
        () => Merge.merge({ a: 1 }, { a: Symbol('test') }), // Symbol值
        () => Merge.merge({ a: 1 }, { a: () => {} }) // 函数值
      ]
      
      let successCount = 0
      boundaryTests.forEach(test => {
        try {
          const result = test()
          if (result !== undefined) {
            successCount++
          }
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 8 // 至少8个操作成功
    })()
  )

  console.log(
    "4. 合并错误恢复测试:",
    (() => {
      const target = { a: 1, b: 2 }
      const source = { b: 3, c: 4 }
      
      try {
        // 错误恢复测试
        const processor = async (value) => {
          if (value === 3) {
            throw new Error('Test error')
          }
          return value * 2
        }
        
        return new Promise((resolve) => {
          Merge.mergeAsync(target, source, processor).then((result) => {
            resolve(Object.keys(result).length > 0)
          }).catch(() => {
            resolve(false)
          })
        })
      } catch (error) {
        return false
      }
    })()
  )

  console.log(
    "5. 合并内存管理测试:",
    (() => {
      const target = { base: 1 }
      const sources = Array.from({ length: 1000 }, (_, i) => ({
        [`key${i}`]: i,
        nested: { value: i * 2 }
      }))
      
      // 内存管理测试
      const initialMemory = process.memoryUsage().heapUsed
      
      // 执行大量合并操作
      for (let i = 0; i < 100; i++) {
        Merge.merge(target, sources[i])
        Merge.mergeImmutable(target, sources[i])
        Merge.mergeWith(target, sources[i], (obj, src) => src)
      }
      
      const finalMemory = process.memoryUsage().heapUsed
      const memoryIncrease = finalMemory - initialMemory
      
      return memoryIncrease < 100 * 1024 * 1024 // 100MB以内
    })()
  )

  console.log(
    "6. 合并并发操作测试:",
    (() => {
      const target = { base: 1 }
      const sources = Array.from({ length: 100 }, (_, i) => ({
        [`key${i}`]: i
      }))
      
      // 并发操作测试
      const operations = [
        () => Merge.merge(target, sources[0]),
        () => Merge.mergeImmutable(target, sources[1]),
        () => Merge.mergeWith(target, sources[2], (obj, src) => src),
        () => Merge.mergeWithArrayStrategy(target, sources[3], 'concat'),
        () => Merge.mergeWithCondition(target, sources[4], () => true),
        () => Merge.mergeWithTypeCheck(target, sources[5], false)
      ]
      
      const results = operations.map(op => op())
      
      return results.every(result => result && Object.keys(result).length > 0)
    })()
  )

  console.log(
    "7. 合并复杂查询测试:",
    (() => {
      const target = {
        user: { profile: { name: 'John', age: 30 } },
        data: { items: [1, 2, 3] }
      }
      const sources = [
        { user: { profile: { age: 31, city: 'NYC' } } },
        { data: { items: [4, 5, 6] } },
        { user: { settings: { theme: 'dark' } } }
      ]
      
      // 复杂查询测试
      const queries = [
        { method: 'merge', sources: sources },
        { method: 'mergeWith', sources: sources, customizer: (obj, src) => src },
        { method: 'mergeWithArrayStrategy', sources: sources, strategy: 'concat' },
        { method: 'mergeWithCondition', sources: sources, predicate: (key) => key !== 'data' },
        { method: 'mergeWithTypeCheck', sources: sources, strict: false }
      ]
      
      const results = queries.map(query => {
        let result
        if (query.method === 'merge') {
          result = Merge.merge(target, ...query.sources)
        } else if (query.method === 'mergeWith') {
          result = Merge.mergeWith(target, query.sources[0], query.customizer)
        } else if (query.method === 'mergeWithArrayStrategy') {
          result = Merge.mergeWithArrayStrategy(target, ...query.sources, query.strategy)
        } else if (query.method === 'mergeWithCondition') {
          result = Merge.mergeWithCondition(target, ...query.sources, query.predicate)
        } else if (query.method === 'mergeWithTypeCheck') {
          result = Merge.mergeWithTypeCheck(target, ...query.sources, query.strict)
        }
        return result && Object.keys(result).length > 0
      })
      
      return results.every(result => result === true)
    })()
  )

  console.log(
    "8. 合并状态一致性测试:",
    (() => {
      const target = { a: 1, b: 2 }
      const source = { b: 3, c: 4 }
      
      // 状态一致性测试
      const operations = [
        () => Merge.merge(target, source),
        () => Merge.mergeImmutable(target, source),
        () => Merge.mergeWith(target, source, (obj, src) => src),
        () => Merge.mergeWithArrayStrategy(target, source, 'replace'),
        () => Merge.mergeWithCondition(target, source, () => true)
      ]
      
      const results = operations.map(op => op())
      
      return results.every(result => result && Object.keys(result).length > 0) &&
             results[0].a === 1 && // merge结果
             results[0].b === 3 && // merge结果
             results[0].c === 4 && // merge结果
             results[1].a === 1 && // mergeImmutable结果
             results[1].b === 3 && // mergeImmutable结果
             results[1].c === 4 // mergeImmutable结果
    })()
  )

  console.log(
    "9. this上下文复杂场景测试:",
    (() => {
      const complexObj = {
        multiplier: 3,
        processComplex: function(target, source) {
          const merged = Merge.mergeWithTransform(target, source, {
            value: (val) => val * this.multiplier
          })
          return merged.value
        }
      }
      
      const target = { value: 2 }
      const source = { value: 3 }
      return complexObj.processComplex(target, source) === 9
    })()
  )

  console.log(
    "10. 复杂对象this绑定复杂场景测试:",
    (() => {
      const complexConfigObj = {
        config: { threshold: 5 },
        processWithConfig: function(target, source) {
          const merged = Merge.mergeWithTransform(target, source, {
            value: (val) => val * 2
          })
          return merged.value >= this.config.threshold
        }
      }
      
      const target = { value: 2 }
      const source = { value: 3 }
      return complexConfigObj.processWithConfig(target, source) === true
    })()
  )

  console.log(
    "11. 合并复杂操作序列测试:",
    (() => {
      const target = { base: 1 }
      const sources = Array.from({ length: 10 }, (_, i) => ({
        [`key${i}`]: i,
        base: i + 1
      }))
      
      // 复杂操作序列
      const operationSequence = [
        { method: 'merge', sources: sources.slice(0, 2) },
        { method: 'mergeWith', sources: sources.slice(2, 3), customizer: (obj, src) => src },
        { method: 'mergeWithArrayStrategy', sources: sources.slice(3, 4), strategy: 'concat' },
        { method: 'mergeWithCondition', sources: sources.slice(4, 5), predicate: () => true },
        { method: 'mergeWithTypeCheck', sources: sources.slice(5, 6), strict: false }
      ]
      
      let successCount = 0
      operationSequence.forEach(seq => {
        try {
          let result
          if (seq.method === 'merge') {
            result = Merge.merge(target, ...seq.sources)
          } else if (seq.method === 'mergeWith') {
            result = Merge.mergeWith(target, seq.sources[0], seq.customizer)
          } else if (seq.method === 'mergeWithArrayStrategy') {
            result = Merge.mergeWithArrayStrategy(target, ...seq.sources, seq.strategy)
          } else if (seq.method === 'mergeWithCondition') {
            result = Merge.mergeWithCondition(target, ...seq.sources, seq.predicate)
          } else if (seq.method === 'mergeWithTypeCheck') {
            result = Merge.mergeWithTypeCheck(target, ...seq.sources, seq.strict)
          }
          
          if (result && Object.keys(result).length > 0) {
            successCount++
          }
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 4 // 至少4个操作成功
    })()
  )

  console.log(
    "12. 合并复杂场景综合测试:",
    (() => {
      const target = {
        user: { profile: { name: 'John', age: 30 } },
        data: { items: [1, 2, 3] }
      }
      const sources = [
        { user: { profile: { age: 31, city: 'NYC' } } },
        { data: { items: [4, 5, 6] } },
        { user: { settings: { theme: 'dark' } } }
      ]
      
      // 综合复杂场景
      const scenarios = [
        // 场景1: 基本合并
        () => {
          const merged = Merge.merge(target, ...sources)
          return merged.user.profile.name === 'John' &&
                 merged.user.profile.age === 31 &&
                 merged.user.profile.city === 'NYC'
        },
        // 场景2: 不可变合并
        () => {
          const merged = Merge.mergeImmutable(target, ...sources)
          return merged.user.profile.name === 'John' &&
                 merged.user.settings.theme === 'dark'
        },
        // 场景3: 自定义合并
        () => {
          const merged = Merge.mergeWith(target, sources[0], (obj, src) => src)
          return merged.user.profile.age === 31
        },
        // 场景4: 数组策略合并
        () => {
          const merged = Merge.mergeWithArrayStrategy(target, sources[1], 'concat')
          return merged.data.items.length === 6
        },
        // 场景5: 最终验证
        () => {
          const merged = Merge.merge(target, ...sources)
          return merged.user.profile.name === 'John' &&
                 merged.user.settings.theme === 'dark' &&
                 merged.data.items.length === 3
        }
      ]
      
      const results = scenarios.map(scenario => scenario())
      
      return results.every(result => result === true)
    })()
  )
}

testMergeComplexScenarios()
